package model;

import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Model {

	static private Connection conn;

	static public void setConnection(Connection connection) throws SQLException {
		if (connection != null) {
			conn = connection;
			conn.setAutoCommit(true);
		}
	}

	static protected long getNextSequence(String name) throws SQLException {
		if (name == null || name.length() <= 0)
			throw new SQLException("bad sequence name");
		ResultSet r = getConnection().createStatement().executeQuery("select " + name + ".nextval from dual");
		if (!r.next())
			throw new SQLException(name + ".nextval return no value");
		return r.getLong(1);
	}

	static protected Clob makeClob(String data) throws SQLException {
		if (data != null) {
			oracle.sql.CLOB newClob = oracle.sql.CLOB.createTemporary(conn, false, oracle.sql.CLOB.DURATION_SESSION);// DURATION_CALL
			newClob.putString(1, data);
			return newClob;
		}
		return null;
	}

	static protected String readClob(Clob data) throws SQLException {
		if (data != null)
			return data.getSubString(1, (int) data.length());
		return null;
	}

	static public Connection getConnection() throws SQLException {
		if (conn == null) {
			DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
			// Class.forName("oracle.jdbc.driver.OracleDriver");
			conn = DriverManager.getConnection("jdbc:oracle:thin:@teleinfo.tu.kielce.pl:1521:XE", "hr", "mycha");
			conn.setAutoCommit(true);
		}
		return conn;
	}

}
